package com.ms.dao;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.ms.entity.PlaceApplication;
import com.ms.entity.PlaceRecord;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.Date;
import java.util.List;

/**
 * 场地申请数据访问接口
 * 继承MyBatis-Plus的BaseMapper，提供基础的CRUD操作
 */
@Mapper
public interface PlaceApplicationMapper extends BaseMapper<PlaceApplication> {
    
    /**
     * 检查指定场地在指定日期范围内是否已被占用
     * @param placeId 场地ID
     * @param startDate 开始日期
     * @param endDate 结束日期
     * @return 是否存在冲突
     */
    @Select("SELECT COUNT(*) FROM place_application " +
            "WHERE pl_id = #{placeId} " +
            "AND lea_status = 1 " + // 只检查已通过的申请
            "AND ((start_date BETWEEN #{startDate} AND #{endDate}) " +
            "OR (end_date BETWEEN #{startDate} AND #{endDate}) " +
            "OR (start_date <= #{startDate} AND end_date >= #{endDate}))")
    int checkDateConflict(@Param("placeId") Integer placeId, 
                          @Param("startDate") Date startDate, 
                          @Param("endDate") Date endDate);
    
    /**
     * 检查指定申请是否已经生成过场地记录
     * @param applicationId 申请ID
     * @return 记录数量
     */
    @Select("SELECT COUNT(*) FROM place_record WHERE lea_id = #{applicationId}")
    int checkIfRecordsExist(@Param("applicationId") Integer applicationId);
    
    /**
     * 批量插入场地记录
     * @param records 场地记录列表
     * @return 插入记录数
     */
    @Insert("<script>" +
            "INSERT INTO place_record (lea_id, or_id, pl_id, app_time) VALUES " +
            "<foreach collection='records' item='record' separator=','>" +
            "(#{record.leaId}, #{record.orId}, #{record.plId}, #{record.appTime})" +
            "</foreach>" +
            "</script>")
    int batchInsertPlaceRecords(@Param("records") List<PlaceRecord> records);
}